package scheduler

import (
	"gitee.com/jnshao/go-start/projects/crawler/engine"
)

type QueueScheduler struct {
	requestChan chan engine.Request
	workerChan  chan chan engine.Request
}

func (q *QueueScheduler) Submit(r engine.Request) {
	q.requestChan <- r
}

func (q *QueueScheduler) WorkerReady(c chan engine.Request) {
	q.workerChan <- c
}

func (q *QueueScheduler) WorkerChan() chan engine.Request {
	return make(chan engine.Request)
}

// 将参数分发到执行方法的接收参数容器中
func (q *QueueScheduler) Run() {
	q.requestChan = make(chan engine.Request)
	q.workerChan = make(chan chan engine.Request)

	go func() {
		requestQ := []engine.Request{}
		workerQ := []chan engine.Request{}
		for {
			var activeRequest engine.Request
			var activeWorker chan engine.Request
			if len(requestQ) > 0 && len(workerQ) > 0 {
				activeRequest = requestQ[0]
				activeWorker = workerQ[0]
			}
			select {
			case request := <-q.requestChan:
				requestQ = append(requestQ, request)
			case worker := <-q.workerChan:
				workerQ = append(workerQ, worker)
			case activeWorker <- activeRequest:
				requestQ = requestQ[1:]
				workerQ = workerQ[1:]

			}
		}
	}()

}
